<template>
    <div class="app-container">
        <div class="filter-container">
            <el-form ref="listQuery" :model="listQuery" inline>
                <el-form-item label="下单时间" prop="filterTime">
                    <el-date-picker size="small" clearable @change="setFilterTime" v-model="listQuery.filterTime" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="所属医院" prop="hid">
                    <el-select size="small" clearable class="filter-item" style="width: 130px" v-model="listQuery.hid" placeholder="请选择医院">
                        <el-option v-for="item in hospitalOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属分组" prop="gid" v-if="roles.indexOf('6') > -1">
                    <el-select size="small" clearable class="filter-item" style="width: 130px" v-model="listQuery.gid" placeholder="请选择分组">
                        <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button size="small" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
                    <el-button size="small" class="filter-item" type="danger" icon="el-icon" @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div style="height: 42px;line-height: 32px;">
            <el-button type="primary" icon="document" @click="handleDownload" :loading="downloadLoading" style="float: right;">下载报表</el-button>
        </div>
        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" stripe>
            <el-table-column width="80px" align="center" type="index" label="序号"></el-table-column>
            <el-table-column align="center" label="下单时间" prop="date"></el-table-column>
            <el-table-column align="center" label="所属医院" prop="hospitalName"></el-table-column>
            <el-table-column align="center" label="所属分组" prop="groupName"></el-table-column>
            <el-table-column align="center" label="衣物数量" prop="clothesCnt"></el-table-column>
            <el-table-column align="center" label="缝补数量" prop="mendCnt"></el-table-column>
        </el-table>
        <div style="height: 32px;line-height: 32px;padding-top: 10px;">
            衣物合计：{{toalAmount}}件<span style="width: 30px;display: inline-block;"></span>缝补合计：{{mendAmount}}件
        </div>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[20,50,100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { fetchHospitalList } from '@/api/hospital'
  import { fetchFactoryGroupList } from '@/api/group'
  import { parseTime, formatSearchTime } from '@/utils'
  import exportExcel from '@/components/Excel/exportExcel'
  import { fetchFactoryBalingSummary, factoryBalingDetailList } from '@/api/factory'

  export default {
    name: 'WorkSum',
    data() {
      return {
        tableKey: 0,
        list: [],
        total: null,
        toalAmount: '',
        listLoading: false,
        listQuery: {
          page: 1,
          size: 20,
          hid: '',
          gid: '',
          batchCode: '',
          startTime: '',
          endTime: '',
          filterTime: []
        },
        hospitalOptions: [],
        groupOptions: [],
        detailList: [],
        downloadLoading: false
      }
    },
    components: {
      exportExcel
    },
    computed: {
      ...mapGetters([
        'roles',
        'fid'
      ]),
      mendAmount() {
        let total = 0
        this.list.forEach((item) => {
          total += (item.mendCnt || 0)
        })
        return total
      }
    },
    created: function() {
      if (this.$route.query && this.$route.query.id) {
        this.listQuery.batchCode = this.$route.query.id
      }
      this.getHospital()
      this.getList()
      this.getGroup()
    },
    filters: {
      parseTime
    },
    methods: {
      getHospital() {
        fetchHospitalList({ page: 1, size: 500, fid: this.fid }).then(response => {
          this.hospitalOptions = response.data && response.data.list || []
        })
      },
      getGroup() {
        fetchFactoryGroupList({ page: 1, size: 500 }).then(response => {
          this.groupOptions = response.data && response.data.list || []
        })
      },
      getList() {
        this.listLoading = true
        var query = {
          page: this.listQuery.page,
          size: this.listQuery.size,
          hid: this.listQuery.hid,
          gid: this.listQuery.gid,
          batchCode: this.listQuery.batchCode,
          startTime: this.listQuery.startTime ? formatSearchTime(this.listQuery.startTime + ' ', true) : '',
          endTime: this.listQuery.endTime ? formatSearchTime(this.listQuery.endTime + ' ') : ''
        }
        fetchFactoryBalingSummary(query).then(response => {
          this.list = response.data && response.data.list || []
          this.total = Number.parseInt(response.data.count)
          this.toalAmount = response.data.clothesCnt
          this.listLoading = false
        }).catch(e => {
          this.listLoading = false
        })
      },
      setFilterTime() {
        if (this.listQuery.filterTime && this.listQuery.filterTime.length) {
          this.listQuery.startTime = this.listQuery.filterTime[0]
          this.listQuery.endTime = this.listQuery.filterTime[1]
          return
        }
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetFilter() {
        this.$refs['listQuery'].resetFields()
        this.setFilterTime()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleDownload() {
        this.downloadLoading = true
        var query = {
          page: 1,
          size: 1000,
          hid: this.listQuery.hid,
          gid: this.listQuery.gid,
          batchCode: this.listQuery.batchCode,
          startTime: this.listQuery.startTime ? formatSearchTime(this.listQuery.startTime + ' ', true) : '',
          endTime: this.listQuery.endTime ? formatSearchTime(this.listQuery.endTime + ' ') : ''
        }
        factoryBalingDetailList(query).then(response => {
          var excelList = response.data && response.data.list || []
          if (!excelList || !excelList.length) {
            this.$message({
              message: '没有可下载的报表',
              type: 'error',
              showClose: true
            })
            this.downloadLoading = false
            return
          }
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['下单时间', '所属分组', '所属医院', '出厂批次', '科室', '品类', '分类', '员工', '衣物数量', '缝补数量']
            const filterVal = ['createTime', 'groupName', 'hospitalName', 'balingCode', 'departmentName', 'typeName', 'categoryName', 'createUserName', 'clothesCnt', 'mendCnt']
            const data = this.formatJson(filterVal, excelList)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '工作汇总' + parseTime(query.startTime, '{y}-{m}-{d}') + '至' + parseTime(query.endTime, '{y}-{m}-{d}'),
              autoWidth: true
            })
            this.downloadLoading = false
          })
        }).catch(e => {
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'createTime') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>

<style scoped>
    .el-range-editor.el-input__inner {
        width: 273px;
        padding: 3px;
    }
</style>
